/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.service.loader.internal;

import lombok.NoArgsConstructor;
import org.apache.commons.beanutils.PropertyUtils;
import org.jrose.api.annotation.remote.ExposeHttpService;
import org.jrose.entity.data.Role;
import org.jrose.entity.data.Team;
import org.jrose.service.loader.AbstractLoader;
import org.jrose.service.loader.AttributeLoader;
import org.jrose.service.loader.CareerLoader;
import org.jrose.service.loader.RoleLoader;

import javax.inject.Named;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Default {@link RoleLoader} implementation.
 *
 * @author Xiaohai Zhang
 * @see AttributeLoader
 * @see CareerLoader
 * @since 2013-09-02 16:47
 */
@Named
@NoArgsConstructor
@ExposeHttpService(name = "/roleLoader", serviceInterface = RoleLoader.class)
public class RoleLoaderImpl extends AbstractLoader implements RoleLoader {
    @Override
    public Role transform(Role source) {
        if (source == null) {
            return null;
        }
        Role destination = new Role();
        try {
            PropertyUtils.copyProperties(destination, source);
        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage(), ex);
        }

        AttributeLoader attributeLoader = getBean(AttributeLoader.class);
        destination.setAttribute(attributeLoader.loadRoleAttribute(destination));

        CareerLoader careerLoader = getBean(CareerLoader.class);
        if (destination.getCareerId() != null) {
            destination.setCareer(careerLoader.load(destination.getCareerId()));
        }
        destination.getMasterCareers().addAll(careerLoader.loadRoleCareers(destination));
        return destination;
    }

    @Override
    public List<Role> loadTeamRoles(Team team) {
        if (team == null) {
            return Collections.emptyList();
        }
        List<Role> roles = new LinkedList<>();
        for (Role role : rolePersistence.findByTeamId(team.getId())) {
            roles.add(transform(role));
        }
        return roles;
    }
}
